package aliyun

import (
	"context"
	"fmt"
	"go_cloud_station/store"
	"log"
	"os"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// 测试库：https://segmentfault.com/a/1190000040501767
var (
	// 增加对象实现接口的约束，如果没实现的话这一行报错，主要是起一个check的作用，没有实际要使用变量
	_ store.Uploader = &AliyunOssStore{}
)

type AliyunOssStore struct {
	// 阿里云的客户端
	client *oss.Client
}

func NewAliyunOssStore(region, accessKey, accessSecret string) *AliyunOssStore {
	config := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, accessSecret)).
		WithRegion(region)

	return &AliyunOssStore{
		client: oss.NewClient(config),
	}
}

func (store *AliyunOssStore) Upload(options *store.UploadOptions) error {
	bucketName := options.BucketName
	fileName := options.FileName
	objectKey := options.ObjectKey

	file, err := os.Open(fileName)
	if err != nil {
		log.Printf("failed to open file %v", err)
		return err
	}
	defer file.Close()

	result, err := store.client.PutObject(context.TODO(), &oss.PutObjectRequest{
		Bucket:     oss.Ptr(bucketName),
		Key:        oss.Ptr(objectKey),
		Body:       file,
		ProgressFn: options.ProcessFn,
	})
	if err != nil {
		log.Fatalf("failed to put object %v", err)
		return err
	}
	fmt.Printf("Successfully uploaded %s ETag: %v\n", fileName, result.ETag)
	return nil
}
